<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>超星学习通签到码</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/blueimp-md5/2.18.0/js/md5.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery.qrcode/1.0/jquery.qrcode.min.js"></script>
    <style>
        * {
            box-sizing: border-box;
            -webkit-tap-highlight-color: transparent;
        }
        
        body {
            font-family: "Microsoft YaHei", sans-serif;
            margin: 0;
            padding: 0;
            min-height: 100vh;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .container {
            background-color: white;
            border-radius: 20px;
            padding: 30px 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            text-align: center;
            max-width: 400px;
            width: 92%;
            margin: 15px;
        }
        
        h1 {
            color: #2c3e50;
            margin-bottom: 20px;
            font-size: 22px;
        }
        
        .sign-name {
            font-size: 18px;
            font-weight: bold;
            color: #3498db;
            margin-bottom: 20px;
            padding: 12px 10px;
            background-color: #f8f9fa;
            border-radius: 10px;
            transition: all 0.3s ease;
            word-break: break-all;
        }
        
        .sign-name.active {
            background-color: #e3f2fd;
            color: #1976d2;
        }
        
        #qrCode {
            margin: 15px auto;
            width: 100%;
            max-width: 250px;
            height: auto;
            aspect-ratio: 1/1;
            padding: 10px;
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;
        }
        
        #qrCode:hover {
            transform: scale(1.02);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
        }
        
        .status {
            margin-top: 15px;
            color: #666;
            font-size: 14px;
            padding: 10px;
            border-radius: 5px;
            background-color: #f8f9fa;
        }
        
        .time-info {
            margin-top: 15px;
            font-size: 14px;
            color: #666;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-wrap: wrap;
            gap: 5px;
        }
        
        .countdown {
            font-weight: bold;
            color: #3498db;
            background-color: #e3f2fd;
            padding: 5px 10px;
            border-radius: 15px;
            min-width: 30px;
        }
        
        .error {
            color: #e74c3c;
            background-color: #fde8e8;
            padding: 10px;
            border-radius: 5px;
            margin-top: 15px;
        }
        
        @media (max-width: 380px) {
            .container {
                padding: 15px 10px;
                margin: 10px;
                width: 95%;
            }
            
            h1 {
                font-size: 20px;
                margin-bottom: 15px;
            }
            
            .sign-name {
                font-size: 16px;
                padding: 10px 8px;
                margin-bottom: 15px;
            }
            
            #qrCode {
                margin: 10px auto;
                max-width: 220px;
                padding: 8px;
            }
            
            .status, .time-info {
                font-size: 13px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>超星学习通签到码</h1>
        <div class="sign-name" id="currentSignName">正在获取签到信息...</div>
        <div id="qrCode"></div>
        <div class="status" id="status">等待签到信息...</div>
        <div class="time-info">
            下次刷新倒计时: <span class="countdown" id="countdown">-</span> 秒
        </div>
    </div>

    <script>
        $(document).ready(function() {
            var timestampDiff = 0;
            var refreshInterval = null;
            var countdownTimer = null;
            var countdown = 0;
            var currentSign = null;
            
            // 获取当前活动的签到
            async function getCurrentSign() {
                try {
                    const response = await fetch('/api/signs/current');
                    const data = await response.json();
                    
                    if (data.success && data.sign) {
                        // 检查是否是相同的签到，如果是则不需要重新启动刷新
                        const isSameSign = currentSign && currentSign.signInId === data.sign.signInId;
                        currentSign = data.sign;
                        $('#currentSignName').text(currentSign.name).addClass('active');
                        
                        // 如果是新的签到才启动刷新
                        if (!isSameSign) {
                            startRefreshing();
                        }
                    } else {
                        // 如果没有活动的签到，清除之前的定时器
                        if (refreshInterval) {
                            clearInterval(refreshInterval);
                            refreshInterval = null;
                        }
                        currentSign = null;
                        $('#currentSignName').text('当前没有活动的签到').removeClass('active');
                        $('#status').text('等待管理员配置签到...').addClass('error');
                    }
                } catch (error) {
                    console.error('获取当前签到失败:', error);
                    $('#status').text('获取签到信息失败').addClass('error');
                }
            }
            
            // 获取服务器时间与本地时间的差值
            function getTimestampDiff(callback) {
                var domain = 'https://reading.chaoxing.com';
                var ctx = '/qd';
                var url = domain + ctx + "/api/time/now";
                
                $.ajax({
                    url: url,
                    type: "get",
                    dataType: "json",
                    success: function(data) {
                        if (data.success) {
                            timestampDiff = data.data - new Date().getTime();
                            $("#status").text("服务器时间同步成功").removeClass("error");
                            if (callback) callback();
                        } else {
                            $("#status").text("获取服务器时间失败: " + (data.message || "未知错误")).addClass("error");
                            timestampDiff = 0;
                            if (callback) callback();
                        }
                    },
                    error: function(xhr, status, error) {
                        $("#status").text("获取服务器时间出错，使用本地时间").addClass("error");
                        timestampDiff = 0;
                        if (callback) callback();
                    }
                });
            }
            
            // 生成签到码URL
            function generateSignInCodeUrl(signInId) {
                var now = new Date();
                var timestamp = now.getTime() + timestampDiff;
                var key = md5("" + timestamp);
                var enc = md5(signInId + key);
                
                var domain = 'https://reading.chaoxing.com';
                var ctx = '/qd';
                
                return domain + ctx + "/api/sign-in/code?signInId=" + signInId + 
                       "&code=&timestamp=" + timestamp + "&enc=" + enc;
            }
            
            // 生成二维码
            function generateQrCode(url) {
                $('#qrCode').empty();
                
                // 计算合适的二维码尺寸
                var width = $('#qrCode').width();
                var height = $('#qrCode').height();
                var size = Math.min(width, height);
                
                $('#qrCode').qrcode({
                    text: url,
                    width: size,
                    height: size
                });
            }
            
            // 开始倒计时
            function startCountdown(seconds) {
                clearInterval(countdownTimer);
                countdown = seconds;
                
                updateCountdown();
                
                countdownTimer = setInterval(function() {
                    countdown--;
                    updateCountdown();
                    
                    if (countdown <= 0) {
                        clearInterval(countdownTimer);
                    }
                }, 1000);
            }
            
            // 更新倒计时显示
            function updateCountdown() {
                $("#countdown").text(countdown);
            }
            
            // 开始自动刷新二维码
            function startRefreshing() {
                if (!currentSign) return;
                
                var interval = currentSign.refreshInterval * 1000;
                
                // 先清除可能存在的定时器
                if (refreshInterval) {
                    clearInterval(refreshInterval);
                    refreshInterval = null;
                }
                
                // 先生成一次
                refreshQrCode();
                
                // 设置定时刷新
                refreshInterval = setInterval(refreshQrCode, interval);
                
                $("#status").text("正在自动刷新签到码...").removeClass("error");
            }
            
            // 刷新二维码
            function refreshQrCode() {
                if (!currentSign) return;
                
                var url = generateSignInCodeUrl(currentSign.signInId);
                generateQrCode(url);
                startCountdown(currentSign.refreshInterval);
                
                $("#status").text("签到码已刷新").removeClass("error");
            }
            
            // 页面加载时获取当前签到
            getCurrentSign();
            
            // 定期检查是否有新的签到
            setInterval(getCurrentSign, 30000);
            
            // 窗口大小变化时重新生成二维码
            $(window).on('resize', function() {
                if (currentSign) {
                    var url = generateSignInCodeUrl(currentSign.signInId);
                    generateQrCode(url);
                }
            });
        });
    </script>
</body>
</html>